﻿using System;
using System.Data;
using BusinessEntities;
using Draco.DataStructure;
using MySql.Data.MySqlClient;

namespace DataAccessLayer
{
    public class RestaurantDAL:DAL<Restaurant>
    {
        public override D_LinkList<Restaurant> GetElements()
        {
            D_LinkList<Restaurant> restaurants = new D_LinkList<Restaurant>();

            string query = "SELECT * FROM restaurants";

            MySqlDataReader reader = MySqlHelper.ExecuteReader(connString, query);

            while (reader.Read())
            {
                int id = (int)reader["id"];
                string name = reader["name"].ToString();
                int x = (int)reader["x"];
                int y = (int)reader["y"];
                int grade = (int) reader["grade"];

                Restaurant r = new Restaurant(id, name, x, y, grade);

                restaurants.Add(r);
            }

            reader.Close();

            return restaurants;
        }

        public override void Insert(params object[] args)
        {
            string name = args[0] as string;
            int x = (int)args[1];
            int y = (int)args[2];
            int grade = (int)args[3];
            string query = string.Format("INSERT INTO restaurants(name, x, y,grade) VALUES ('{0}','{1}','{2}','{3}')", name,x,y, grade);

            MySqlHelper.ExecuteNonQuery(connString, query);
        }

        public override void Update(params object[] args)
        {
            int id = (int)args[0];
            string name = args[1] as string;
            int x = (int)args[2];
            int y = (int)args[3];
            int grade = (int)args[4];
            string query = string.Format("UPDATE restaurants SET name='{1}',x='{2}',y='{3}',grade='{4}' WHERE id={0}", id, name, x, y,grade);

            MySqlHelper.ExecuteNonQuery(connString, query);
        }

        public override void Delete(int id)
        {
            string query = string.Format("DELETE FROM restaurants WHERE id={0}", id);

            MySqlHelper.ExecuteNonQuery(connString, query);
        }

        public override int GetLastInsertID()
        {
            int result = 0;
            string query = "select max(id) FROM restaurants";
            DataRow datarow = MySqlHelper.ExecuteDataRow(connString, query);
            try
            {
                result = int.Parse(datarow[0].ToString());
            }
            catch (Exception e)
            {
                result = -1;
            }
            return result;
        }
    }
}
